import requests
from datetime import datetime
import json
from django.conf import settings

from apps import redis_client
from util.exception import CNException


class SIMTool:
    def __init__(self):
        self.sim_status_url = "https://api.iot.10086.cn/v5/ec/query/sim-status"
        self.sim_charge_url = "https://api.iot.10086.cn/v5/ec/query/balance-info"
        self.sim_message_url = "https://api.iot.10086.cn/v5/ec/operate/sim-mt-sms"
        self.token_url = "https://api.iot.10086.cn/v5/ec/get/token"
        self.appid = "C5010591A5912523921"
        self.password = "99W*cXVhMMHH"
        self.token_name = "token_10086"
        self.fail_reason = ""
        self.transid = self.get_transid()
        self.token = self.get_token()
        self.status_dict = {
            "1": "待激活",
            "2": "已激活",
            "4": "停机",
            "6": "可测试",
            "7": "库存",
            "8": "预销户"
        }

    def get_transid(self):
        now_time = datetime.today()
        now_time_s = now_time.strftime("%Y%m%d%H%M%S")
        transid_number = str(redis_client.incr(settings.TRANSID_NUMBER))
        transid = "{}{}{}".format(self.appid, now_time_s, transid_number)
        return transid

    def get_api(self, url_front, parmas):
        r = requests.get(url=url_front, params=parmas)
        status_code = r.status_code
        if status_code == 200:
            text = json.loads(r.text)
            return text
        else:
            self.message = "中国移动通信异常"
            raise CNException

    def get_token(self):
        token = redis_client.get(self.token_name)
        if token:
            token = token.decode("utf-8")
            return token
        else:
            self.get_transid()
            data = self.get_api(self.token_url,
                                parmas={"appid": self.appid, "password": self.password, "transid": self.get_transid()})
            status = data.get("status")
            if status == "0":
                result = data.get("result")
                token = result[0].get("token")
                redis_client.setex(name=self.token_name, time=3600, value=token)
                return token
            else:
                self.message = data.get("message")
                raise CNException

    def get_sim_charge(self, msisdn):
        data = self.get_api(self.sim_charge_url,
                            parmas={"transid": self.transid, "token": self.token, "msisdn": msisdn})
        status = data.get("status")
        if status == "0":
            result = data.get("result")
            amount = result[0].get("amount")
            return amount
        else:
            self.message = data.get("message")
            raise CNException

    def get_sim_status(self, msisdn):
        data = self.get_api(self.sim_status_url,
                            parmas={"transid": self.transid, "token": self.token, "msisdn": msisdn})
        status = data.get("status")
        if status == "0":
            result = data.get("result")
            cardStatus = result[0].get("cardStatus")
            cardStatus = self.status_dict.get(cardStatus)
            return cardStatus
        else:
            self.message = data.get("message")
            raise CNException

    def get_sim(self, msisdn):
        result = ""
        try:
            amount = self.get_sim_charge(msisdn)
            status = self.get_sim_status(msisdn)
            result = "{}/{}".format(amount, status)
        except Exception as e:
            if not isinstance(e, CNException):
                self.message = "网络通信异常"
        finally:
            return result

    def get_message(self):
        return self.message

    def send_sim_message(self, msisdn):
        transid = self.get_transid()
        token = self.get_token()
        actionid = "001"
        encode = 1
        params = "123"
        data = self.get_api(self.sim_charge_url, parmas={"transid": transid, "token": token, "msisdn": msisdn,
                                                         "actionid": actionid, "encode": encode, "params": params})
        status = data.get("status")
        if status == "0":
            result = data.get("result")
            amount = result[0].get("amount")
            return amount


if __name__ == '__main__':
    SIMTool.get_transid()
